﻿using System.ComponentModel;
using System.Windows;
using System.Windows.Input;

namespace Microsoft.Coding4Fun.TweetCraft.Tray
{
    /// <summary>
    /// Interaction logic for SettingsWindow.xaml
    /// </summary>
    public sealed partial class SettingsWindow
    {
        private readonly ITweetCraft tweetCraft;

        public SettingsWindow(ITweetCraft tweetCraft)
        {
            this.tweetCraft = tweetCraft;
            InitializeComponent();
        }

        private SettingsContext SettingsContext
        {
            get { return (SettingsContext)DataContext; }
        }
        
        protected override void OnClosing(CancelEventArgs e)
        {
            base.OnClosing(e);

            // Cancel closing of the settings window, hide instead
            e.Cancel = true;
            Hide();
        }

        private void OnAuthorizedClicked(object sender, RoutedEventArgs e)
        {
            tweetCraft.AuthorizeUser();
        }
        
        private void OnCancelClicked(object sender, RoutedEventArgs e)
        {
            Cancel();
            Hide();
        }

        private void OnApplyClicked(object sender, RoutedEventArgs e)
        {
            Apply();
        }

        private void OnOKClicked(object sender, RoutedEventArgs e)
        {
            Apply();
            Hide();
        }

        private void Apply()
        {
            if(string.IsNullOrEmpty(twitterPasswordBox.Password))
            {
                // Since OAuth happens per-transaction, we don't want "Apply / OK"
                // to reverse a previously successful OAuth validation
                return;
            }

            var token = tweetCraft.GetAccessToken(twitterPasswordBox.Password);
            if (token != null && token.Length >= 2)
            {
                SettingsContext.TwitterToken = token[0];
                SettingsContext.TwitterTokenSecret = token[1];
            }
            SettingsContext.Apply();
            twitterPasswordBox.Password = string.Empty;
        }

        private static void Cancel()
        {
            SettingsContext.Cancel();
        }
        
        private void PasswordBox_LostFocus(object sender, RoutedEventArgs e)
        {
            SettingsContext.TwitterTokenSecret = twitterPasswordBox.Password;
        }

        private void OnTitleBarMouseDown(object sender, MouseButtonEventArgs e)
        {
            DragMove();
        }
    }
}